using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.TableEFCore;
using MinimalistFoodStreet.BackEnd.Server.Server.RequestExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.Server.ResponseExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.IServer.Tables;

namespace MinimalistFoodStreet.BackEnd.Server.Server.Tables 
{
	[InjectClass]
	public class LoginLogsServer : ILoginLogsServer
	{
		private readonly ServerRepository _serverRepository;
		public LoginLogsServer (DbContext dbContext) 
		{
			_serverRepository = new ServerRepository(dbContext);
		}
		
		public async Task<ResponseApiDto> AddAsync(RequestCreateLoginLogsDto dto)
		{
			int affectedRows=await _serverRepository.loginLogsEFCore.AddAsync(dto.ToCreateEntity());
			return ResponseApiDto.Create(affectedRows);
		}
		
		public async Task<ResponseApiDto> UpdateAsync(RequestUpdateLoginLogsDto dto)
		{
			LoginLog loginLog = await _serverRepository.loginLogsEFCore.Query(d=>d.LlId==dto.id).SingleOrDefaultAsync();
			if(loginLog==null)
			{
				return ResponseApiDto.Fail("该实例不存在");
			}
			int affectedRows = await _serverRepository.loginLogsEFCore.UpdateAsync(loginLog);
			return ResponseApiDto.Create(affectedRows);
		}
		
		public async Task<ResponseApiDto> DeleteAsync(RequestDeleteLoginLogsDto dto)
		{
			int affectedRows = await _serverRepository.loginLogsEFCore.Query(d=>d.LlId==dto.id).ExecuteDeleteAsync();
			if(affectedRows == 0)
			{
				return ResponseApiDto.Fail("该实例不存在");
			}
			return ResponseApiDto.Create(affectedRows);
		}

		public async Task<ResponseApiDto> DetailAsync(int id)
		{
			LoginLog loginLog = await _serverRepository.loginLogsEFCore.Query(d=>d.LlId==id).SingleOrDefaultAsync();
			if(loginLog == null)
			{
				return ResponseApiDto.Fail("该实例不存在");
			}
			return ResponseApiDto.Ok("数据已获取",loginLog.ToResponseDto());
		}
		
		public async Task<ResponseApiDto> PaginationAsync(int page,int limit,string? key)
		{
			int total = 0;
			List<LoginLog> loginLogs = await _serverRepository.loginLogsEFCore.Pagination(d=>true,false,d=>d.LlId,out total,page,limit).ToListAsync();
			List<ResponseLoginLogsDto> responseLoginLogsDtos = loginLogs.Select(d=>d.ToResponseDto()).ToList();
			return ResponseApiDto.Ok("数据已获取",new {data=responseLoginLogsDtos,total=total});
		}
	}
}